package com.paw.ruoyi.admin.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import com.paw.ruoyi.admin.common.domain.Result;
import com.paw.ruoyi.admin.config.RuoYiConfig;
import com.paw.ruoyi.admin.exceptions.file.FileNameLengthLimitExceededException;
import com.paw.ruoyi.admin.service.IFileUploadService;
import com.paw.ruoyi.admin.utils.file.FileUploadUtils;
import com.paw.ruoyi.admin.utils.file.MimeTypeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Rubble
 * @date 2022/3/11
 * doc：
 * https://help.aliyun.com/document_detail/84781.html
 **/


@Slf4j
public class LocalFileUploadService implements IFileUploadService {

  @Autowired
  private RuoYiConfig ruoYiConfig;


  @Override
  public Result<String> getDomainUrl () {
    return Result.result(ruoYiConfig.getImgServerUrl());
  }

  @Override
  public Result<String>  getUrl (String key) {
    String url = ruoYiConfig.getImgServerUrl()+"/"+key;
    return Result.result(url);
  }

  @Override
  public Result<String>  getKey (String url) {
    String key = url.replace(ruoYiConfig.getImgServerUrl(),"");
    return Result.result(key);
  }

  @Override
  public Result<String> uploadFile (MultipartFile file) throws IOException {
   String path = FileUploadUtils.upload(RuoYiConfig.getUploadPath(),file);
    String url = ruoYiConfig.getImgServerUrl()+path;
    return Result.result(url);
  }


  @Override
  public Result<String>  upload (InputStream inputStream,String fileName) throws IOException {
    Assert.notNull(fileName);
    int fileNameLength = fileName.length();
    if (fileNameLength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
      throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
    }

    String ext = FileUtil.extName(fileName);
    FileUploadUtils.isAllowedExtension(ext, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);

    String destFileName = FileUploadUtils.extractFilename(fileName);
    String baseDir = RuoYiConfig.getUploadPath();
    String destFilePath =  baseDir + File.separator + destFileName;
    FileOutputStream fileOutputStream = new FileOutputStream(destFilePath);
    FileCopyUtils.copy(inputStream,fileOutputStream);
    String pathFileName = FileUploadUtils.getPathFileName(baseDir, fileName);
    String url = ruoYiConfig.getImgServerUrl() + pathFileName;
    return Result.result(url);
  }

}
